package contentservicelogic

import (
	"center-data-platform/app/content/model"
	post "center-data-platform/app/content/rpc/content"
	"center-data-platform/app/content/rpc/internal/svc"
	"context"
	"encoding/json"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddLogic {
	return &AddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddLogic) Add(in *post.CreatePostReq) (*post.CreatePostResp, error) {
	contents := &model.Content{
		UserId:      in.UserId,
		Type:        in.Type,
		Title:       in.Title,
		Content:     in.Content,
		Cover:       in.Cover,
		Description: in.Description,
		Tags:        in.Tags,
		CreatedTime: time.Now(),
		UpdatedTime: time.Now(),
		Status:      1,
	}
	err := l.svcCtx.DB.Model(&model.Content{}).Create(contents).Error
	if err != nil {
		return nil, err
	}
	insertId := contents.Id
	data, _ := json.Marshal(contents)
	if err = l.svcCtx.KafkaPusher.Push(l.ctx, string(data)); err != nil {
		logx.Errorf("KqPusherClient Push post Error , err :%v", err)
	}
	return &post.CreatePostResp{
		Code: 200,
		Msg:  "添加成功",
		Data: &post.CreateMessage{
			Id: insertId,
		},
	}, nil
}
